//! 账户API
//! 
//! 提供统一的账户查询接口，支持所有产品线

use crate::errors::Result;
use crate::rest::RestClient;
use crate::models::*;
use std::collections::HashMap;

/// 账户API
pub struct AccountApi<'a> {
    client: &'a RestClient,
}

impl<'a> AccountApi<'a> {
    pub fn new(client: &'a RestClient) -> Self {
        Self { client }
    }

    /// 获取账户信息
    pub async fn get_account(&self) -> Result<AccountInfo> {
        // 根据产品类型使用不同的路径
        let endpoint = match self.client.config().product_type {
            crate::ProductType::Spot => "/api/v3/account",  // 现货API使用完整路径
            crate::ProductType::UsdM => "/fapi/v3/account",  // 期货API使用完整路径
            crate::ProductType::CoinM => "/dapi/v1/account", // 币本位期货API使用v1版本
            crate::ProductType::Options => "/api/v3/account", // 期权测试网使用现货API
            crate::ProductType::Portfolio => "/api/v3/account", // 组合保证金使用现货API
        };
        
        // 打印完整的API调用URL
        let full_url = format!("{}{}", self.client.config().rest_base_url(), endpoint);
        tracing::info!("[ACCOUNT_API] 调用账户信息API: {}", full_url);
        
        let response = self.client.get(endpoint, true).await?;
        let account: AccountInfo = serde_json::from_str(&response)?;
        Ok(account)
    }

    /// 获取账户余额
    pub async fn get_balance(&self, asset: Option<&str>) -> Result<Vec<Balance>> {
        let account = self.get_account().await?;
        
        if let Some(asset_filter) = asset {
            Ok(account.balances.into_iter()
                .filter(|balance| balance.asset == asset_filter)
                .collect())
        } else {
            Ok(account.balances)
        }
    }

    /// 获取账户状态
    pub async fn get_account_status(&self) -> Result<AccountStatus> {
        let response = self.client.get("/accountStatus", true).await?;
        let status: AccountStatus = serde_json::from_str(&response)?;
        Ok(status)
    }

    /// 获取API交易状态
    pub async fn get_api_trading_status(&self) -> Result<ApiTradingStatus> {
        let response = self.client.get("/apiTradingStatus", true).await?;
        let status: ApiTradingStatus = serde_json::from_str(&response)?;
        Ok(status)
    }

    /// 获取API权限
    pub async fn get_api_permissions(&self) -> Result<ApiPermissions> {
        let response = self.client.get("/apiRestrictions", true).await?;
        let permissions: ApiPermissions = serde_json::from_str(&response)?;
        Ok(permissions)
    }

    /// 获取用户数据流
    pub async fn start_user_data_stream(&self) -> Result<UserDataStream> {
        // 根据产品类型使用不同的路径
        let endpoint = match self.client.config().product_type {
            crate::ProductType::Spot => "/api/v3/userDataStream",
            crate::ProductType::UsdM => "/fapi/v1/listenKey",
            crate::ProductType::CoinM => "/dapi/v1/listenKey",
            crate::ProductType::Options => "/api/v3/userDataStream", // 期权测试网使用现货API
            crate::ProductType::Portfolio => "/api/v3/userDataStream",
        };
        
        let response = self.client.post(endpoint, &HashMap::new(), false).await?;
        let stream: UserDataStream = serde_json::from_str(&response)?;
        Ok(stream)
    }

    /// 保持用户数据流活跃
    pub async fn keep_alive_user_data_stream(&self, _listen_key: &str) -> Result<()> {
        // 根据产品类型使用不同的路径
        let endpoint = match self.client.config().product_type {
            crate::ProductType::Spot => "/api/v3/userDataStream",
            crate::ProductType::UsdM => "/fapi/v1/listenKey",
            crate::ProductType::CoinM => "/dapi/v1/listenKey",
            crate::ProductType::Options => "/api/v3/userDataStream", // 期权测试网使用现货API
            crate::ProductType::Portfolio => "/api/v3/userDataStream",
        };
        
        self.client.put(endpoint, true).await?;
        Ok(())
    }

    /// 关闭用户数据流
    pub async fn close_user_data_stream(&self, _listen_key: &str) -> Result<()> {
        // 根据产品类型使用不同的路径
        let endpoint = match self.client.config().product_type {
            crate::ProductType::Spot => "/api/v3/userDataStream",
            crate::ProductType::UsdM => "/fapi/v1/listenKey",
            crate::ProductType::CoinM => "/dapi/v1/listenKey",
            crate::ProductType::Options => "/api/v3/userDataStream", // 期权测试网使用现货API
            crate::ProductType::Portfolio => "/api/v3/userDataStream",
        };
        
        self.client.delete(endpoint, true).await?;
        Ok(())
    }
}
